package utils

import (
	"fmt"
	"reflect"
)

// CopyFields函数用于将源对象的同名字段值复制到目标对象中
func BeanCopy(source, target interface{}) error {
	sourceValue := reflect.ValueOf(source)
	targetValue := reflect.ValueOf(target)

	if sourceValue.Kind() != reflect.Ptr || targetValue.Kind() != reflect.Ptr {
		return fmt.Errorf("source and target must be pointers")
	}

	sourceType := reflect.TypeOf(source).Elem()
	targetType := reflect.TypeOf(target).Elem()

	if sourceType.Kind() != reflect.Struct || targetType.Kind() != reflect.Struct {
		return fmt.Errorf("source and target must be structs")
	}

	for i := 0; i < sourceType.NumField(); i++ {
		sourceField := sourceType.Field(i)
		targetField, found := targetType.FieldByName(sourceField.Name)
		if found && sourceField.Type == targetField.Type {
			targetValue.Elem().FieldByName(sourceField.Name).Set(sourceValue.Elem().Field(i))
		}
	}

	return nil
}

// 示例结构体
type Person struct {
	Name string
	Age  int
}

type PersonVo struct {
	Name string
}

func main() {
	source := Person{
		Name: "John",
		Age:  30,
	}

	var target PersonVo
	err := BeanCopy(&source, &target)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println("Source:", source)
	fmt.Println("Target:", target)
}
